package com.mathlearning.auth.interceptor;

import com.mathlearning.auth.common.BusinessException;
import com.mathlearning.auth.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 跨域预检请求直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        // 获取 Authorization 头
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new BusinessException(401, "未登录或登录已过期，请重新登录");
        }

        // 提取 token
        String token = authHeader.substring(7);

        try {
            // 验证 token
            Claims claims = jwtUtil.getClaimsFromToken(token);
            
            if (claims == null) {
                throw new BusinessException(401, "登录已过期，请重新登录");
            }
            
            // 从 token 中获取用户ID
            Long userId = claims.get("userId", Long.class);
            String phone = claims.get("phone", String.class);

            // 将用户信息存储到请求属性中，供 Controller 使用
            request.setAttribute("userId", userId);
            request.setAttribute("phone", phone);

            return true;

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException(401, "登录已过期，请重新登录");
        }
    }
}

